package com;

import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(value = "/MenuServlet")
public class MenuServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        int u_id= (int) request.getSession().getAttribute("u_id");
        String  role= (String) request.getSession().getAttribute("role");
        Connection con=null;
        PreparedStatement psm=null;
        PreparedStatement psm1=null;
        ResultSet rs=null;
        ResultSet rs1=null;
        try {
        con = JdbcUtil.getConnection();
        psm = con.prepareStatement("SELECT m.m_name,m.m_url FROM menu m,role_menu rm WHERE m.m_id = rm.`m_id` AND rm.`role`=?");
        psm.setString(1,role);
        rs=psm.executeQuery();
        Map<String ,String> map = new HashMap<String,String>();
        while (rs.next()){
            String m_name=rs.getString("m_name");
            String m_url=rs.getString("m_url");
            map.put(m_name,m_url);
        }
        request.setAttribute("map",map);
        psm1=con.prepareStatement("SELECT u_name FROM user WHERE u_id="+u_id);
        rs1=psm1.executeQuery();
        String username="";
        while (rs1.next()){
            username=rs1.getString("u_name");
        }
            request.setAttribute("test",username);
            request.getRequestDispatcher("/jsp/frame.jsp").forward(request,response);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}